<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <el-progress v-if="progress && progress<100" type="circle" :percentage="progress" />
      <img v-if="value && progress === 0" :src="value" class="avatar">
      <i v-show="!progress" v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// const COS = require('cos-js-sdk-v5')
import COS from 'cos-js-sdk-v5'
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDUllTu50dz3mKddMozsUpsjIZQ0JK3Wic', // 身份识别ID
  SecretKey: 'e17vSdX9UZOxEExPaVAYeT1LPDk35pHE' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // imageUrl: '',
      progress: 0
    }
  },
  methods: {
    upload(res) {
      // console.log(res)
      if (!res) return
      cos.putObject({
        Bucket: 'cp75-1312367966', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file,
        onProgress: (progressData) => {
          this.progress = parseInt(progressData.percent * 100)
        } // 上传文件对象
      }, (err, data) => {
        console.log(err || data)
        // 上传成功之后
        if (data.statusCode === 200) {
          this.progress = 0
          // this.imageUrl = `https://${data.Location}`
          this.$emit('input', `https://${data.Location}`)
        }
      })
    },
    beforeAvatarUpload(file) {
      const isIMG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isIMG) {
        this.$message.error('上传头像必须为图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isIMG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
